//
//  SceneryOrderController.m
//  lv678
//
//  Created by apple on 15/9/10.
//  Copyright (c) 2015年 lampshade. All rights reserved.
//  景点订单

#import "SceneryOrderController.h"
#import "SceneryDetailController.h"
#import "ResourceOfPriceController.h"
#import "RequestAFNetworking.h"
@interface SceneryOrderController ()<ResourceOfPriceControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *selectUseDate;

@property (weak, nonatomic) IBOutlet UITextField *buySum;//购买数量
@property (weak, nonatomic) IBOutlet UITextField *name;//出行人姓名
@property (weak, nonatomic) IBOutlet UITextField *phoneNum;//出行人联系电话
@property (weak, nonatomic) IBOutlet UILabel *priceSum;//订单总额
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;//提交按钮
@property (nonatomic, assign) int price;//选择日期单价
@property (nonatomic, assign) int MaxQuantity;//最大购买份数
@property (nonatomic, assign) int MinQuantity;//最小购买份数
@property (nonatomic, assign) int ResourceID;//景点资源ID
@property (nonatomic, assign) int ProductID;//景点产品ID
@property (nonatomic, copy) NSString *date;//使用时间
@property (nonatomic, strong) AFHTTPRequestOperationManager *managers;//AFNetworking
@property (nonatomic, copy) NSString *url;//请求接口URL

@end

@implementation SceneryOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTableView];
}

#pragma mark -初始化界面设置
- (void)initTableView{
    self.buySum.delegate = self;
    self.name.delegate = self;
    self.phoneNum.delegate = self;
    
    //标签内容换行
    UILabel *lblName = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, self.tableView.frame.size.width, 80)];
    lblName.numberOfLines = 0;
    lblName.textAlignment = NSTextAlignmentCenter;
    lblName.text = [self.resource valueForKey:@"sceneryName"];
    lblName.font = [UIFont systemFontOfSize:16.0];
    [self.tableView setTableHeaderView:lblName];
    [self.submitBtn addTarget:self action:@selector(submitOrder) forControlEvents:UIControlEventTouchUpInside];
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(UseDate)];
    recognizer.numberOfTapsRequired = 1;
    self.selectUseDate.userInteractionEnabled = YES;
    [self.selectUseDate addGestureRecognizer:recognizer];
}

#pragma mark -点击选择时间事件
- (void)UseDate{
    ResourceOfPriceController *resourceOfPrice = [[ResourceOfPriceController alloc]init];
    resourceOfPrice.delegate = self;
    
    self.ResourceID = [[self.resource valueForKey:@"ResourceID"]intValue];
    self.ProductID = [[self.resource valueForKey:@"ProductID"]intValue];
    resourceOfPrice.resourceID = self.ResourceID;
    resourceOfPrice.productID = self.ProductID;
    
    [self.navigationController pushViewController:resourceOfPrice animated:YES];
}

#pragma mark -设置使用时间
- (void)sendDate:(ScenerySourceDataModel *)model{
    self.price = model.price;
    self.MaxQuantity = model.maxQuantity;
    self.MinQuantity = model.minQuantity;
    self.date = [model.date substringToIndex:10];
    self.selectUseDate.text = [model.date substringToIndex:10];
}

#pragma mark -关闭软键盘
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.buySum endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - 当输入框内容改变时判断购买份数
- (void)textFieldDidEndEditing:(UITextField *)textField{
    int ticketSum = [self.buySum.text intValue];
    [self injudgeTextField];
    self.priceSum.text = [NSString stringWithFormat:@"%d",ticketSum*self.price];
    
}

#pragma makr - 验证输入框信息，购买份数应大于价格资源库返回购买最小份数，小于最大份数
- (void)injudgeTextField{
    NSString *sum = @"购买份数在";
    sum = [[[[sum stringByAppendingString:[NSString stringWithFormat:@"%d",self.MinQuantity]]stringByAppendingString:@"-"]stringByAppendingString:[NSString stringWithFormat:@"%d",self.MaxQuantity]]stringByAppendingString:@"之间"];
    if ([self.buySum.text intValue] >= self.MinQuantity && [self.buySum.text intValue] <= self.MaxQuantity) {
        return;
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:sum delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        [self.buySum becomeFirstResponder];
    }
}

#pragma mark - 提交订单
- (void)submitOrder{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"UrlList.plist" ofType:nil];
    NSDictionary *temp = [NSDictionary  dictionaryWithContentsOfFile:path];
    NSString *url = [temp valueForKey:@"viewspotapp"];
    
     AFHTTPRequestOperationManager *manager = [[RequestAFNetworking alloc]sendRequest];
    self.managers = manager;
    self.url = url;
    //检查景点可定性
    NSDictionary *data = @{@"serviceName":@"TicketOrderCanBooking",@"queryParameters":
                               @{@"UseQuantity":self.buySum.text,
                                 @"TotalPrice":self.priceSum.text,
                                 @"ResourceID":[NSString stringWithFormat:@"%d",self.ResourceID],
                                 @"DistributionChannel":@"9",
                                 @"OrderTotalPrice":self.priceSum.text,
                                 @"UseDate":self.selectUseDate.text
                                }};
    [manager POST:url parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        NSString *response = [responseObject objectForKey:@"OrderCanBookingResponse"];
        if ([[response valueForKey:@"Code" ] isEqualToString:@"true"]) {
            [self saveDataToDataBase];
        }else{
            NSString *comment = [response valueForKey:@"FailPocessPoint"];
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:comment delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"提交订单失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }];
}

#pragma mark - 保存数据到数据库请求
- (void)saveDataToDataBase{
    NSDictionary *data = @{@"serviceName":@"SaveTicketOrder",@"queryParameters":
                               @{@"ClientName_E":@"",
                                 @"ProductID":[NSString stringWithFormat:@"%d",self.ProductID],
                                 @"TelphoneNumber":self.phoneNum.text,
                                 @"PassportType":[self.resource valueForKey:@"PassportType"],
                                 @"ContactMobile":self.phoneNum.text,
                                 @"ContactName":self.name.text,
                                 @"UidKey":@"",
                                 @"Amount":[NSString stringWithFormat:@"%d",self.price],
                                 @"Quantity":self.buySum.text,
                                 @"IDCardNo":@"371327199009172216",
                                 @"SalesCity":@"3",
                                 @"AdultNumber":self.buySum.text,
                                 @"HzNo":@"",
                                 @"UseDate":self.date,
                                 @"TicketID":[NSString stringWithFormat:@"%d",self.ResourceID],
                                 @"TicketName":[self.resource valueForKey:@"sceneryName"],
                                 @"AgeType":@"ADU",
                                 @"Price":[NSString stringWithFormat:@"%d",self.price],
                                 @"TicketType":@"0",
                                 @"Gender":@"0",
                                 @"ContactInfo":@"",
                                 @"ClientName":self.name.text,
                                 @"IDCardType":@"1",
                                 @"Remark":@"真贵，都买不起啊"
                                 }};
    [_managers POST:_url parameters:data success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [self isPay:[responseObject valueForKey:@"DistributorOrderID"]];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark - 是否支付
- (void)isPay:(NSString *)orderID{
    NSDictionary *data = @{@"serviceName":@"BackNotify",@"queryParameters":
                               @{@"OrderID":orderID,@"IsPay":@"1"}};
    [_managers POST:_url parameters:data success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
